import UIKit
import AppTrackingTransparency
import Flutter
import AuthenticationServices

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    var channel:FlutterMethodChannel!
    
    var appleLoginResultBlock:((Dictionary<String, String>)->())!
    
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      GeneratedPluginRegistrant.register(with: self)
      self.initPlatformMethods()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    override func applicationDidBecomeActive(_ application: UIApplication) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                
            })
        }
        UIApplication.shared.applicationIconBadgeNumber = 0;
    }
    
    func initPlatformMethods(){
        self.channel = FlutterMethodChannel.init(name: "com.room/opapp", binaryMessenger: self.window.rootViewController as! FlutterBinaryMessenger)
        self.channel.setMethodCallHandler { call, result in
            if (call.method == "checkFace"){
                result(self.checkFace(path: call.arguments as! String));
            }else if (call.method == "appleLogin"){
                self.appleLogin()
                self.appleLoginResultBlock = { dic in
                    result(dic);
                }
                
            }else if (call.method == "getNativeRouterName"){
                result("");
            }else if (call.method == "skipAndroidSplashScreen"){
                result(true);
            }
        }
    }
    func checkFace(path:String) -> Int{
        var image = CIImage.init(image: .init(contentsOfFile: path)!)
        var detector = CIDetector.init(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
        var features = detector!.features(in: image!);
        return features.count;
    }
    
    func appleLogin() {
        if #available(iOS 13.0, *) {
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email] // 可根据需求选择请求的范围
            
            let authorizationController = ASAuthorizationController(authorizationRequests: [request])
            authorizationController.delegate = self
            authorizationController.presentationContextProvider = self
            authorizationController.performRequests()
        } else {
            // Fallback on earlier versions
        }

    }
}

@available(iOS 13.0, *)
extension AppDelegate: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIApplication.shared.windows.filter({ $0.isKeyWindow }).last!
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let identityToken = String.init(data: appleIDCredential.identityToken!, encoding: .utf8) ?? ""
//            let authorizationCode = String.init(data: appleIDCredential.authorizationCode!, encoding: .utf8) ?? ""
            self.appleLoginResultBlock(["identityToken":identityToken,"authorizationCode":appleIDCredential.user,"error":""])
        }else{
            self.appleLoginResultBlock(["error":"授权信息不符"]);
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // 处理登录错误
//        self.appleLoginResultBlock(["error":error.localizedDescription])
        
        var msg = "未知错误，请稍后重试";
        
        switch error {
        case ASAuthorizationError.unknown:
            //未知错误
            break;
        case ASAuthorizationError.canceled:
            //用户取消
            msg = "";
        case ASAuthorizationError.failed:
            msg = "授权请求失败";
        case ASAuthorizationError.invalidResponse:
            msg = "授权请求无响应";
        case ASAuthorizationError.notHandled:
            msg = "授权请求未处理";
        default:
            break;
        }
        
        self.appleLoginResultBlock(["error":msg])
    }
}
